import requests
from config import JENKINS_URL, USERNAME, API_TOKEN

class JenkinsJob:
    def __init__(self, jenkins_url, username, api_token):
        self.jenkins_url = jenkins_url
        self.username = username
        self.api_token = api_token

    def get_views(self):
        api_url = f"{self.jenkins_url}/api/json"
        response = requests.get(api_url, auth=(self.username, self.api_token))
        if response.status_code == 200:
            return response.json()['views']
        else:
            print("Failed to retrieve views information.")
            return None

    def get_jobs(self, view_url):
        view_response = requests.get(f"{view_url}/api/json", auth=(self.username, self.api_token))
        if view_response.status_code == 200:
            return view_response.json()['jobs']
        else:
            print(f"Failed to retrieve jobs information for view: {view_url}")
            return None

    def get_server_name(self, job_name):
        if "-" in job_name:
            server_name = job_name.split("-", 1)[-1]
        else:
            server_name = job_name
        return server_name

    def get_full_build_log(self, job_url):
        last_build_url = f"{job_url}/lastBuild/consoleText"
        build_response = requests.get(last_build_url, auth=(self.username, self.api_token))
        if build_response.status_code == 200:
            return build_response.text
        else:
            return "Failed to retrieve build log"

    def select_view(self):
        views_info = self.get_views()
        if not views_info:
            return None
        
        print("请选择一个视图编号:")
        for index, view in enumerate(views_info, start=1):
            print(f"{index}: {view['name']}")
        print("0: 返回上一步")

        selected_index = int(input("输入视图编号: "))
        if selected_index == 0:
            return None
        
        selected_view = views_info[selected_index - 1]
        view_name = selected_view['name']
        view_url = selected_view['url']
        view_description = selected_view.get('description', 'No description available')
        print(f"Selected View Name: {view_name}, URL: {view_url}, Description: {view_description}")
        return selected_view

    def select_job(self, view_url, view_name):
        jobs_info = self.get_jobs(view_url)
        if not jobs_info:
            return None
        
        print("请选择一个作业编号或输入作业名称:")
        for index, job in enumerate(jobs_info, start=1):
            print(f"{index}: {job['name']}")
        print("0: 返回上一步")

        user_input = input("输入作业编号或名称: ")
        if user_input == '0':
            return None
        
        if user_input.isdigit():
            selected_job = jobs_info[int(user_input) - 1]
        else:
            selected_job = next((job for job in jobs_info if job['name'] == user_input), None)
        
        if selected_job:
            job_name = selected_job['name']
            job_url = selected_job['url']
            server_name = self.get_server_name(job_name)
            print(f"  Job Name: {job_name}, Server Name: {server_name}, View: {view_name}, URL: {job_url}")
            
            show_log = input("是否显示完整的构建日志？(y/n): ")
            if show_log.lower() == 'y':
                full_log = self.get_full_build_log(job_url)
                print(f"完整的构建日志:\n{full_log}")
            
            return selected_job
        else:
            print("未找到指定的作业")
            return None

def main():
    jenkins_job = JenkinsJob(JENKINS_URL, USERNAME, API_TOKEN)
    
    while True:
        selected_view = jenkins_job.select_view()
        if not selected_view:
            break
        
        view_url = selected_view['url']
        view_name = selected_view['name']
        while True:
            selected_job = jenkins_job.select_job(view_url, view_name)
            if not selected_job:
                break

if __name__ == "__main__":
    main()